package org.example;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class SetBookmarkValue {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("test.docx");
             XWPFDocument document = new XWPFDocument(fis)) {

            // 定义要设置的书签及其值
            String bookmarkName = "xrb";
            String bookmarkValue = "This is the new value for the bookmark.";

            // 遍历文档中的所有段落
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                XmlCursor cursor = paragraph.getCTP().newCursor();
                while (cursor.hasNextToken()) {
                    if (cursor.isStart() && cursor.getObject() instanceof CTBookmark) {
                        CTBookmark bookmark = (CTBookmark) cursor.getObject();
                        String name = bookmark.getName();
                        System.out.println("Found bookmark: " + name);
                        if (name.equals(bookmarkName)) {
                            // 记录书签的开始位置
                            XmlCursor startCursor = cursor.newCursor();

                            // 移动到书签结束标记
                            cursor.toNextToken();

                            // 记录书签的结束位置
                            XmlCursor endCursor = cursor.newCursor();

                            // 删除书签范围内的所有内容
                            while (startCursor.comparePosition(endCursor) < 0) {
                                startCursor.removeXml();
                                startCursor.toNextToken();
                            }

                            // 在书签位置插入新内容
                            XWPFRun run = paragraph.createRun();
                            run.setText(bookmarkValue);

                            // 移动游标到书签结束位置
                            cursor.toNextToken();
                            cursor.removeXml(); // 删除书签结束标记

                            System.out.println("Bookmark " + bookmarkName + " updated with value: " + bookmarkValue);
                        }
                    }
                    cursor.toNextToken();
                }
                cursor.dispose();
            }

            // 保存修改后的文档
            try (FileOutputStream fos = new FileOutputStream("document.docx")) {
                document.write(fos);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}